import React, {useState, useEffect, useLayoutEffect, useMemo} from 'react';
import {View, ScrollView} from 'react-native';
import {useTranslation} from 'react-i18next';
import {useMMKVObject} from '@/hooks/useMMkv';
import {CountryItem} from '@/pages/common/CountryPicker';
import {useDispatch, useSelector, shallowEqual} from 'react-redux';
import {
  fetchCountries,
  selectSelectedCountry,
  setSelectedCountry,
} from '@/store/slices/countrySlice';

import store, {AppDispatch} from '@/store';
import {userApi} from '@/services/api/userApi';
import Toast from '@/utils/toast';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import {useForm, Controller} from 'react-hook-form';
import {ErrorText} from '@/components/ErrorText';
import {TextInput, Button, Icon} from 'tsun-smart-ui';
import Avatar from '@/components/Avatar';
import usePicker from '@/hooks/usePicker';
interface UserInfo {
  username?: string;
  email?: string;
  userType?: number;
  nickname?: string;
  county?: string;
  timeZone?: string;
  center?: string;
  avatar?: string;
  instCode?: string;
  instName?: string;
  userId?: number;
}

interface FormData {
  nickname: string;
}

const UserProfileScreen = ({
  navigation,
}: ReactNavigation.RootStackScreenProps<'UserProfile'>) => {
  const {t} = useTranslation();
  const dispatch = useDispatch<AppDispatch>();
  const [userInfo, setUserInfo] = useMMKVObject<UserInfo>('user_info');
  const {bottom} = useSafeAreaInsets();
  // react-hook-form 表单管理
  const {
    control,
    handleSubmit,
    formState: {errors},
  } = useForm<FormData>({
    defaultValues: {
      nickname: userInfo?.nickname || '',
    },
  });

  // 状态管理
  const selectedCountry = useSelector(selectSelectedCountry, shallowEqual);
  const [timezoneList, setTimezoneList] = useState<CountryItem['zoneList']>([]);
  const pickerList = useMemo(() => {
    return timezoneList.map(item => t(item.code));
  }, [timezoneList, t]);
  const [Picker, selectedValue, setSelectedValue] = usePicker(pickerList);
  const [loading, setLoading] = useState(false);
  const [avatar, setAvatar] = useState(userInfo?.avatar || '');
  // 初始化国家和时区数据
  useLayoutEffect(() => {
    console.log('Initializing countries with userInfo:', userInfo);
    if (store.getState().country.countries.length === 0) {
      dispatch(fetchCountries())
        .unwrap()
        .then(value => {
          const result = value.find(item => item.value === userInfo?.county);
          dispatch(setSelectedCountry(result!));
          const timezone = result?.zoneList.find(
            item => item.value === userInfo?.timeZone,
          );
          //在selectedCountry之后更新最新的时区
          requestAnimationFrame(() => {
            setSelectedValue([t(timezone?.code!)]);
          });
        });
    } else {
      // 如果已经有国家数据，直接设置
      const countries = store.getState().country.countries;
      if (userInfo?.county) {
        const result = countries.find(item => item.value === userInfo.county);
        if (result) {
          dispatch(setSelectedCountry(result));
          const timezone = result?.zoneList.find(
            item => item.value === userInfo?.timeZone,
          );
          requestAnimationFrame(() => {
            setSelectedValue([t(timezone?.code!)]);
          });
        }
      }
    }
  }, [dispatch, t, userInfo?.county, userInfo?.timeZone]);

  // 更新时区列表
  useEffect(() => {
    if (selectedCountry) {
      const newTimezoneList = selectedCountry?.zoneList.map(item => ({
        ...item,
        code: t(item.code),
      }))!!;
      setTimezoneList(newTimezoneList);
      // 只有在没有设置时区的情况下才设置默认时区
      setSelectedValue([t(selectedCountry?.zoneList[0].code!)]);
    }
  }, [selectedCountry]);

  // 添加处理邮箱修改的函数
  const handleEmailChange = () => {
    navigation.navigate('ChangeEmail');
  };

  // 处理保存
  const onSubmit = async (formData: FormData) => {
    try {
      setLoading(true);
      // 准备更新参数
      const updateParams = {
        nickname: formData.nickname,
        county: selectedCountry?.value,
        timeZone: timezoneList.find(item => t(item.code) === selectedValue[0])
          ?.value,
        avatar,
      };

      // 调用更新接口
      const response = await userApi.updateUserInfo(updateParams);

      if (response.code === 0) {
        // 更新成功后获取最新的用户信息
        const userInfoResponse = await userApi.getUserInfo();
        setUserInfo(userInfoResponse.data);
        // 显示成功提示

        Toast.success({
          message: t('userSetting.saveSuccess'),
        });
        // 返回上一页
        navigation.goBack();
      } else {
        // 显示错误信息
        Toast.error({
          message:
            response.message ||
            t('common.saveFailed', {defaultValue: '保存失败'}),
        });
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <View className="flex-1 px-4" style={{paddingBottom: bottom || 24}}>
      <ScrollView
        className="flex-1 pt-3"
        showsVerticalScrollIndicator={false}
        contentContainerClassName=" justify-between pb-4">
        <Avatar
          className=" size-[100px] self-center mb-4"
          uri={avatar}
          onChange={setAvatar}></Avatar>
        {/* 表单部分 */}
        <View className="gap-y-4">
          {/* 昵称 */}
          <Controller
            control={control}
            name="nickname"
            rules={{
              required: t('userSetting.form.error.nickname.required', {
                defaultValue: '请输入昵称',
              }),
              pattern: {
                value: /^\S*$/,
                message: t('validation.no.spaces.allowed', {
                  defaultValue: '昵称不能包含空格',
                }),
              },
            }}
            render={({field: {onChange, value}}) => (
              <TextInput
                left="nickname"
                label={t('sysuser.nickname', {
                  defaultValue: '昵称',
                })}
                placeholder={t('userSetting.form.error.nickname.required', {
                  defaultValue: '请输入昵称',
                })}
                value={value}
                onChangeText={onChange}
                autoCapitalize="none"
              />
            )}
          />
          {errors.nickname && (
            <View className="pl-4">
              <ErrorText text={errors.nickname.message!} />
            </View>
          )}
          {/* 国家或地区 */}
          <TextInput
            label={t('userSetting.basicInfo.form.label.countryRegion', {
              defaultValue: '国家/地区',
            })}
            editable={false}
            value={t(selectedCountry?.code!)}
            onPress={() => {
              navigation.navigate('CountryPicker', {
                current: t(selectedCountry?.code!),
              });
            }}
            left="area"
            right={<Icon name="right" size={10} />}
          />

          {/* 时区 */}
          <TextInput
            editable={false}
            label={t('sys.app.time.zone', {
              defaultValue: '时区',
            })}
            value={selectedValue[0]}
            left="timezone"
            onPress={() => {
              Picker.show();
            }}
            right={<Icon name="right" size={10} />}
          />
          <TextInput
            editable={false}
            label={t('userSetting.SecuritySettings.form.label.email', {
              defaultValue: '邮箱',
            })}
            value={userInfo?.email}
            left="email"
            onPress={handleEmailChange}
            right={<Icon name="right" size={10} />}
          />

          {/* 安装商运营商 - 如果是安装商角色才显示 */}
          {userInfo?.userType === 2 && (
            <TextInput
              label={t('param.installercode', {
                defaultValue: '安装商代码',
              })}
              left="code"
              readOnly
              value={userInfo?.instCode}
              autoCapitalize="none"
            />
          )}

          {/* 公司名称 - 如果是安装商角色才显示 */}
          {userInfo?.userType === 2 && (
            <TextInput
              label={t('sysdept.installer.companyname', {
                defaultValue: '公司名称',
              })}
              left="company"
              readOnly
              value={userInfo?.instName}
              autoCapitalize="none"
            />
          )}
        </View>
      </ScrollView>
      <Button
        className="mt-4"
        disabled={loading}
        title={t('dytable.submit')}
        onPress={handleSubmit(onSubmit)}
      />
    </View>
  );
};
export default UserProfileScreen;
